package com.bgdCA.auth.controller;

import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @ClassName CaptchaController
 * @Description TODO
 * @Author AlvinZheng
 * @Date 2020/8/4 11:57
 * @Version 1.0
 **/
@Controller
@Slf4j
public class CaptchaController {
    @Autowired
    private Producer captchaProducer;

    @RequestMapping("/captcha.jpg")
    public void getCaptcha(HttpServletRequest request,
                           HttpServletResponse response) throws IOException {
        response.setContentType("image/jpeg");
        String capText = captchaProducer.createText();

        log.info("生成验证码为：" + capText);

        //存入session
        request.getSession().setAttribute("captcha", capText);
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }

}
